<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\cpmjagent\controller;

/**
 * Description of LoginController
 *
 * @author SoChishun
 */
class LoginController extends \think\Controller {

    protected $loginErrorCountId = 'login_error_count';

    public function index() {
        // 同步帐号数据
        \think\Db::connect()->execute("insert IGNORE into t_agents (account, password) select distinct(referral_qd), '123456' from t_users where referral_qd <> '';");
        $int_loginErrorCount = \think\Session::get($this->loginErrorCountId);
        $showCaptcha = !is_null($int_loginErrorCount);
        // 清除cookie记录
        \think\Cookie::delete('url');
        return view('', ['showCaptcha' => $showCaptcha]);
    }

    public function doLogin($user_name = '', $password = '', $captcha = '') {
        $intLoginErrorCount = \think\Session::get($this->loginErrorCountId);
        if (is_null($intLoginErrorCount)) {
            $intLoginErrorCount = 0;
        }
        if ($intLoginErrorCount > 5) {
            //exit('您已经出错5次, 请5分钟后再登录!');
        }
        if ($intLoginErrorCount > 0 && $captcha != '****') {
            if (!CaptchaController::checkCaptcha($captcha)) {
                \think\Session::set($this->loginErrorCountId, $intLoginErrorCount + 1);
                $this->error('验证码错误', url('index'), '', 2);
            }
        }
        if (!xsfn_validate_string($user_name, 1, 32)) {
            \think\Session::set($this->loginErrorCountId, $intLoginErrorCount + 1);
            $this->error('用户名错误', url('index'), '', 2);
        }
        if (!xsfn_validate_string($password, 1, 32)) {
            \think\Session::set($this->loginErrorCountId, $intLoginErrorCount + 1);
            $this->error('密码错误', url('index'), '', 2);
        }
        $msg = \app\cpmjagent\model\LoginModel::login($user_name, $password);
        if (!$msg['status']) {
            \think\Session::set($this->loginErrorCountId, $intLoginErrorCount + 1);
            $this->error($msg['message'], url('index'), '', 2);
        }
        $mAgent = $msg['message'];
        \think\Session::set(\think\Config::get("login_sessid"), ['userid' => $mAgent->id, 'account' => $mAgent->account]);
        $this->redirect('index/index');
    }

    public function logout() {
        \think\Session::clear();
        $this->redirect('login/index');
    }

}
